﻿@using System.Configuration
@using Matrix.MaKaYunShang.BLL
@using Matrix.MaKaYunShang.Model.Dto
@model Matrix.MaKaYunShang.Model.CloudCards

@{
    ViewBag.Title = "创建卡券";
    ViewBag.PathToBtn = "/CloudCards/List";
    ViewBag.TextBtn = "返回至列表";
    Layout = "~/Views/Shared/_Layout.cshtml";
    var currentUser = ViewBag.CurrentUser as McAccountDto;
    var showDisabledIndustry = false;
    var platformShopIds = ConfigurationManager.AppSettings["PlatformShopIds"];
    if (!string.IsNullOrEmpty(platformShopIds) && platformShopIds.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries).Contains(currentUser.ShopId.ToString()))
    {
        showDisabledIndustry = true;
    }
}

<div class="row">
    <div class="col-lg-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                卡券信息
            </div>
            <div class="panel-body">
                <div class="row">
                    @using (Html.BeginForm("Create", "CloudCards", FormMethod.Post, new { id = "frmUpdate", enctype = "multipart/form-data" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)
                        <div class="col-lg-12">
                            <fieldset>
                                <div class="form-group col-md-12" style="display: none">
                                    <input id="fileImage" class="form-control" type="file" name="fileImage" style="display: none;" />
                                    <input id="btnSelect" type=button class="btn btn-info" value="上传列表图" onclick="fileImage.click()" />
                                    <img id="imgThumb" alt="缩略图" style="max-height: 80px" src="/Content/admin/image/uploadimg.png" imgpath="/Content/admin/image/uploadimg.png" />
                                    <span>（建议尺寸：宽180*高180，200KB以内）</span>
                                </div>
                                <div class="form-group col-md-6">
                                    <label>卡券名称</label>
                                    <div class="input-group">
                                        @Html.TextBoxFor(model => model.CardName, new { @class = "form-control", placeholder = "卡券名称" })
                                        <span class="input-group-addon red">必填</span>
                                    </div>
                                </div>
                                <div class="form-group col-md-6">
                                    <label>卡券类别</label>
                                    <div class="input-group">
                                        <select class="form-control" id="CardCategoryId" name="CardCategoryId">
                                            @{
                        var cateList = CardCategoryBLL.Instance.GetModelList();
                        foreach (var item in cateList)
                        {
                            <option value="@item.Id" code="@item.CategoryCode">@item.CategoryName</option>
                        }
                                            }
                                        </select>
                                        <span class="input-group-addon red">必填</span>
                                    </div>
                                </div>
                                <div class="form-group col-md-6">
                                    <label>卡券价值</label>
                                    <div class="input-group">
                                        @Html.TextBoxFor(model => model.CardValue, new { @class = "form-control", placeholder = "卡券价值" })
                                        <span class="input-group-addon">元</span>
                                    </div>
                                </div>
                                <div class="form-group col-md-6">
                                    <label>开始时间</label>
                                    <div class="input-group">
                                        @Html.TextBoxFor(model => model.StartTime, new { @class = "form-control form_datetime", placeholder = "开始时间" })
                                        <span class="input-group-addon red">必填</span>
                                    </div>
                                </div>
                                <div class="form-group col-md-6">
                                    <label>结束时间</label>
                                    <div class="input-group">
                                        @Html.TextBoxFor(model => model.EndTime, new { @class = "form-control form_datetime", placeholder = "结束时间" })
                                        <span class="input-group-addon red">必填</span>
                                    </div>
                                </div>
                                <div class="form-group col-md-6">
                                    <label>是否在店铺首页显示</label>
                                    <div class="input-group">                                                           @Html.DropDownList("ShowOnHomepage", (IEnumerable<SelectListItem>)ViewBag.ShowOnHomepage, new { @class = "form-control" })
                                        <span class="input-group-addon"></span>
                                    </div>
                                </div>
                                <div class="form-group col-md-6" id="divLeastCost" style="display: none">
                                    <label>最低消费</label>
                                    <div class="input-group">
                                        @Html.TextBoxFor(model => model.LeastCost, new { @class = "form-control", placeholder = "请填写最低消费（满额可用）" })
                                        <span class="input-group-addon">元</span>
                                    </div>
                                </div>
                                <div class="form-group col-md-6" id="divReduceCost" style="display: none">
                                    <label>减免金额</label>
                                    <div class="input-group">
                                        @Html.TextBoxFor(model => model.ReduceCost, new { @class = "form-control", placeholder = "请填写减免金额" })
                                        <span class="input-group-addon">元</span>
                                    </div>
                                </div>
                                <div class="form-group col-md-6" id="divDiscountValue" style="display: none">
                                    <label>折扣额度</label>
                                    <div class="input-group">
                                        @Html.TextBoxFor(model => model.DiscountValue, new { @class = "form-control", placeholder = "请填写折扣额度（填30就是七折）" })
                                        <span class="input-group-addon red">必填</span>
                                    </div>
                                </div>
                                <div class="form-group col-md-6">
                                    <label>优惠说明</label>
                                    <div class="input-group">
                                        @Html.TextAreaFor(model => model.Description, new { @class = "form-control", rows = "5", placeholder = "优惠说明" })
                                        <span class="input-group-addon red">必填</span>
                                    </div>
                                </div>
                                <div class="form-group col-md-6">
                                    <label>使用须知</label>
                                    <div class="input-group">
                                        @Html.TextAreaFor(model => model.Instruction, new { @class = "form-control", rows = "5", placeholder = "使用须知" })
                                        <span class="input-group-addon red">必填</span>
                                    </div>
                                </div>
                                <div class="form-group col-md-6">
                                    <label>是否可转赠</label>
                                    <div class="input-group">
                                        @Html.DropDownList("CanShare", (IEnumerable<SelectListItem>)ViewBag.CanShare, new { @class = "form-control" })
                                        <span class="input-group-addon"></span>
                                    </div>
                                </div>
                                @if (currentUser.IsHeadquarters)
                                {
                                    <div class="form-group col-md-6">
                                        <label><a data-target="#UsableShopModal" data-toggle="modal" class="btn btn-info">选择适用店铺</a></label>
                                        <label id="SelectText">如无限制则无需选择</label>
                                    </div>
                                    @Html.HiddenFor(model => model.UsableShopIds)
                                }
                                @if (showDisabledIndustry)
                                {
                                    <div class="form-group col-md-12">
                                        <label><a data-target="#DisabledSeparatedIndustryModal" data-toggle="modal" class="btn btn-info">选择不可发卡的行业类别</a></label>
                                        <label id="IndustrySelectText">如无限制则无需选择</label>
                                    </div>
                                    @Html.HiddenFor(model => model.DisabledSeparatedIndustryIds)
                                }
                                <div class="col-md-12">
                                    <button id="btnSave" type="submit" class="btn btn-primary">确定并保存</button>
                                </div>
                            </fieldset>
                        </div>
                    }
                </div>
            </div>
        </div>
    </div>
</div>

@if (currentUser.IsHeadquarters)
{
    <div class="modal fade" id="UsableShopModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog" style="max-width: 600px;width: 450px;">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title">卡券适用店铺</h4>
                </div>
                <div class="modal-body">
                    <div style="margin-bottom: 5px;">
                        <input type="text" class="form-control" placeholder="店铺名称" value="" style="width: 250px;display: inline-block" id="keyWords" />
                        <a class="btn btn-primary" onclick="searchShops();">查询</a>
                        <a class="btn btn-info" style="width: 100px" onclick="SaveShops();">保存</a>
                    </div>
                    <div class="table-responsive table-bordered" style="max-height: 250px;">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th style="width:30px;">
                                        <input type="checkbox" id="checkAll" />
                                    </th>
                                    <th>店铺名称</th>
                                </tr>
                            </thead>
                            <tbody id="ShopsData"></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
}

@if (showDisabledIndustry)
{
    <div class="modal fade" id="DisabledSeparatedIndustryModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog" style="max-width: 600px;width: 450px;">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title">选择不可发卡的行业类别</h4>
                </div>
                <div class="modal-body">
                    <div style="margin-bottom: 5px;">
                        <input type="text" class="form-control" placeholder="行业名称" value="" style="width: 250px;display: inline-block" id="IndustryKeyWords" />
                        <a class="btn btn-primary" onclick="searchIndustry();">查询</a>
                        <a class="btn btn-info" style="width: 100px" onclick="SaveIndustry();">保存</a>
                    </div>
                    <div class="table-responsive table-bordered" style="max-height: 250px;">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th style="width:30px;">
                                        <input type="checkbox" id="checkAllIndustry" />
                                    </th>
                                    <th>行业名称</th>
                                </tr>
                            </thead>
                            <tbody id="IndustryData"></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
}

@section javascript{
    <script src="/Content/admin/dist/js/imageUploader.js"> </script>
    <script type="text/javascript">
        // Image Upload
        imageUploader.uploadSingle(fileImage, btnSelect, imgThumb, '@ViewBag.theHeadPic');

        $(function () {
            changeCardCategory();
            searchShops();
            searchIndustry();

            $("#CardCategoryId").change(function () {
                changeCardCategory();
                cateChange();
            });

            $("#checkAll").click(function () {
                var checked = $(this).prop("checked");
                var shops = $(".cbShop");
                for (var i = 0; i < shops.length; i ++) {
                    $(shops[i]).prop("checked", checked);
                }
            });

            $("#checkAllIndustry").click(function () {
                var checked = $(this).prop("checked");
                var industry = $(".cbIndustry");
                for (var i = 0; i < industry.length; i ++) {
                    $(industry[i]).prop("checked", checked);
                }
            });

            $("#frmUpdate").validate({
                rules: {
                    CardName: { required: true },
                    CardValue: { required: true, number: true, min: 0 },
                    TotalQuantity: { required: true, digits: true, min: 1 },
                    StartTime: { required: true },
                    EndTime: { required: true }
                },
                messages: {
                    CardName: { required: "请填写卡券名称" },
                    CardValue: { required: "请填写卡券价值" },
                    CommodityName: { required: "请填写卡券总数" },
                    StartTime: { required: "请选择开始时间" },
                    EndTime: { required: "请选择结束时间" }
                },
                submitHandler: function (form) {
                    showLoading();
                    $("#btnSave").html("正在保存...").attr("disabled", "disabled");
                    form.submit();
                }
            });
        });

        function changeCardCategory() {
            var code = $("#CardCategoryId option:selected").attr("code");
            if (code == "1002") {
                $("#divLeastCost").show();
                $("#divReduceCost").show();
                $("#divDiscountValue").hide();
            } else if (code == "1003") {
                $("#divLeastCost").show();
                $("#divReduceCost").hide();
                $("#divDiscountValue").show();
            } else {
                $("#divLeastCost").hide();
                $("#divReduceCost").hide();
                $("#divDiscountValue").hide();
            }
        }

        function cateChange() {
            $("#LeastCost").rules("remove");
            $("#ReduceCost").rules("remove");
            $("#DiscountValue").rules("remove");
            var code = $("#CardCategoryId option:selected").attr("code");
            if (code == "1002") {
                $("#LeastCost").rules("add", {
                    required: true,
                    min: 0,
                    messages: {
                        required: "请填写最低消费"
                    }
                });
                $("#ReduceCost").rules("add", {
                    required: true,
                    min: 0,
                    messages: {
                        required: "请填写减免金额"
                    }
                });
            } else if (code == "1003") {
                $("#DiscountValue").rules("add", {
                    required: true,
                    min: 0,
                    max: 100,
                    messages: {
                        required: "请填写折扣额度"
                    }
                });
            }
        }

        function searchShops() {
            $("#ShopsData").html("");
            $.post("@Url.Action("GetBranchShopList", "Shops")", "&keyWords=" + encodeURIComponent($("#keyWords").val()), function (data) {
                if (data != null) {
                    var selIds = $("#UsableShopIds").val().split(",");
                    for (var i = 0; i < data.length; i++) {
                        var needSel = false;
                        for (var j = 0; j < selIds.length; j++) {
                            if (selIds[j] == data[i].Id) {
                                needSel = true;
                                break;
                            }
                        }
                        $("#ShopsData").append("<tr><td><input type='checkbox' class='cbShop' value=" + data[i].Id + " " + (needSel ? "checked='checked'" : "") + "/></td><td>" + data[i].Name + "</td></tr>");
                    }
                }
            });
        }

        function SaveShops() {
            var selIds = "";
            var checkedShops = $(".cbShop:checked");
            for (var i = 0; i < checkedShops.length; i++) {
                selIds += $(checkedShops[i]).val() + ",";
            }
            if (selIds != "") {
                $("#SelectText").html("已设置" + checkedShops.length + "家店");
            } else {
                $("#SelectText").html("无限制");
            }
            $("#UsableShopIds").val(selIds);
            $("#UsableShopModal").modal("hide");
        }

        function searchIndustry() {
            $("#IndustryData").html("");
            $.post("@Url.Action("GetSeparatedIndustryList")", "&keyWords=" + encodeURIComponent($("#IndustryKeyWords").val()), function (data) {
                if (data != null) {
                    var selIds = $("#DisabledSeparatedIndustryIds").val().split(",");
                    for (var i = 0; i < data.length; i++) {
                        var needSel = false;
                        for (var j = 0; j < selIds.length; j++) {
                            if (selIds[j] == data[i].Id) {
                                needSel = true;
                                break;
                            }
                        }
                        $("#IndustryData").append("<tr><td><input type='checkbox' class='cbIndustry' value=" + data[i].Id + " " + (needSel ? "checked='checked'" : "") + "/></td><td>" + data[i].Name + "</td></tr>");
                    }
                }
            });
        }

        function SaveIndustry() {
            var selIds = "";
            var checkedIndustry = $(".cbIndustry:checked");
            for (var i = 0; i < checkedIndustry.length; i++) {
                selIds += $(checkedIndustry[i]).val() + ",";
            }
            if (selIds != "") {
                $("#IndustrySelectText").html("已禁止" + checkedIndustry.length + "种行业");
            } else {
                $("#IndustrySelectText").html("无限制");
            }
            $("#DisabledSeparatedIndustryIds").val(selIds);
            $("#DisabledSeparatedIndustryModal").modal("hide");
        }
    </script>
}